<template>
    <el-card style="height:70px">
        <el-form ref="form" label-width="80px" inline label-position="left" class="query-form">
            <el-form-item label="用户账号:">
                <el-input placeholder="请输入用户账号" v-model="keyWord" style="width: 300px;"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" :disabled="keyWord ? false : true"
                    @click="search">搜索</el-button>
                <el-button type="danger" icon="Refresh" @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>

    <el-card style="margin: 10px 0px;">
        <el-button type="primary" icon="Plus" @click="addUser">添加用户</el-button>
        <el-button type="danger" icon="Delete" @click="deleteUserList"
            :disabled="selectArr.length ? false : true">批量删除</el-button>
        <el-table :data="records" style="width: 100%;margin: 10px 0px;" border height="590"
            @selection-change="selectChange">
            <el-table-column width="50px" type="selection" align="center" fixed></el-table-column>
            <el-table-column label="序号" width="80px" type="index" align="center" fixed></el-table-column>
            <el-table-column label="用户ID" width="100px" align="center" prop="id"></el-table-column>
            <el-table-column label="用户账号" width="200px" align="center" prop="username"
                show-overflow-tooltip></el-table-column>
            <el-table-column label="用户名称" width="200px" align="center" prop="name"
                show-overflow-tooltip></el-table-column>
            <el-table-column label="用户角色" width="200px" align="center" prop="roleName"
                show-overflow-tooltip></el-table-column>
            <el-table-column label="创建时间" width="200px" align="center" prop="createTime"
                show-overflow-tooltip></el-table-column>
            <el-table-column label="更新时间" width="200px" align="center" prop="updateTime"
                show-overflow-tooltip></el-table-column>
            <el-table-column label="操作" align="center" width="300px" fixed="right">
                <template #="{ row, $index }">
                    <el-button type="default" size="small" icon="User" @click="setRole(row)">分配角色</el-button>
                    <el-button type="primary" size="small" icon="Edit" @click="updateUser(row)">编辑</el-button>
                    <el-popconfirm :title="`你确定删除${row.username}吗？`" width="260" @confirm="deleteUser(row.id)">
                        <template #reference>
                            <el-button type="danger" size="small" icon="Delete">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" background
            :page-sizes="[20, 40, 60, 80]" layout=" prev, pager, next, jumper,->,sizes,total" :total="total"
            @current-change="getUserList" @size-change='handler' />
    </el-card>

    <el-drawer :title="title" v-model="isShow" direction="rtl">
        <el-form :model="userParams" label-width="80px" status-icon label-position="left" :rules="rules"
            ref="ruleFormRef">
            <el-form-item label="用户账号" prop="username">
                <el-input placeholder="请您输入用户账号" v-model="userParams.username"></el-input>
            </el-form-item>
            <el-form-item label="用户姓名" prop="name">
                <el-input placeholder="请您输入用户姓名" v-model="userParams.name"></el-input>
            </el-form-item>
            <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
                <el-input placeholder="请您输入用户密码" v-model="userParams.password"></el-input>
            </el-form-item>
        </el-form>
        <div style="float: right;">
            <el-button type="default" @click="isShow = false">取消</el-button>
            <el-button type="primary" @click="submitAddOrUpdate()">确定</el-button>
        </div>
    </el-drawer>

    <el-drawer title="分配角色" v-model="isShow2" direction="rtl">
        <el-form label-width="80px">
            <el-form-item label="用户账号">
                <el-input v-model="userParams.name" disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="职位列表">
                <template #="{ row, $index }">
                    <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange"
                        style="margin: 0px 10px;">
                        全选
                    </el-checkbox>
                    <el-checkbox-group v-model="userRole" @change="handleCheckedCitiesChange">
                        <el-checkbox v-for="(role, index) in roleArr" :key="role" :label="role" :value="role"
                            style="margin: 0px 10px;">
                            {{ role.roleName }}
                        </el-checkbox>
                    </el-checkbox-group>
                </template>
            </el-form-item>
        </el-form>
        <div style="float: right;">
            <el-button type="default" @click="isShow2 = false">取消</el-button>
            <el-button type="primary" @click="submitSetRole()">确定</el-button>
        </div>
    </el-drawer>
</template>

<script setup lang="ts">
    import { ref, onMounted, reactive, nextTick } from 'vue';
    import { ElMessage, FormInstance, FormRules } from 'element-plus'
    import { reqAllUser, reqAddOrUpdateUser, reqAllRole, reqSetUserRole, reqRemoveUser, reqRemoveUserList } from '@/api/acl/query'
    import { UserResponseData, Records, User, AllRole, SetRoleData } from '@/api/acl/query/type';
    import useLayOutSettingStore from '@/store/modules/setting';
    const pageNo = ref<number>(1)
    const pageSize = ref<number>(20)
    const total = ref<number>(0)
    const records = ref<Records>([])
    const isShow = ref<boolean>(false)
    const isShow2 = ref<boolean>(false)
    const title = ref<string>('添加用户')
    const userParams = reactive<User>({
        username: '',
        name: '',
        password: ''
    })
    const ruleFormRef = ref<FormInstance>()
    const checkAll = ref<boolean>(false)
    const isIndeterminate = ref<boolean>(true)
    const roleArr = ref<AllRole>([])
    const userRole = ref<AllRole>([])
    const selectArr = ref<number[]>([])
    const keyWord = ref<string>('')
    const settingStore = useLayOutSettingStore()
    // 规则函数
    const validateUsername = (rule: any, value: any, callback: any) => {
        if (value.trim().length >= 5) {
            callback()
        } else {
            callback(new Error('用户账号至少5位'))
        }
    }

    const validateName = (rule: any, value: any, callback: any) => {
        console.log(rule, '///////////////')
        if (value.trim().length >= 2) {
            callback()
        } else {
            callback(new Error('用户名字至少2位'))
        }
    }

    const validatePassword = (rule: any, value: any, callback: any) => {
        if (value.trim().length >= 6) {
            callback()
        } else {
            callback(new Error('用户密码至少6位'))
        }
    }

    // const rules = {
    //     username: [{ required: true, trigger: 'blur', validator: validateUsername }],
    //     name: [{ required: true, trigger: 'blur' }],
    //     password: [{ required: true, trigger: 'blur' }]
    // }

    // 规则
    const rules = reactive<FormRules<typeof userParams>>({
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        name: [{ required: true, trigger: 'blur', validator: validateName }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
    })

    const getUserList = async (pager = 1) => {
        pageNo.value = pager
        console.log(keyWord.value, 111)
        let res: UserResponseData = await reqAllUser(pageNo.value, pageSize.value, keyWord.value)
        records.value = res.data.records
        total.value = res.data.total
        // console.log(records.value, '获取用户列表')
    }

    const search = () => {
        getUserList()
    }

    const reset = () => {
        settingStore.refresh = !settingStore.refresh
    }

    const handler = () => {
        getUserList(records.value.length > 1 ? pageNo.value : pageNo.value - 1)
    }

    const addUser = () => {
        title.value = '添加用户'
        isShow.value = true
        Object.assign(userParams, {
            id: 0,
            username: '',
            name: '',
            password: ''
        })

        nextTick(() => {
            ruleFormRef.value?.clearValidate('username')
            ruleFormRef.value?.clearValidate('name')
            ruleFormRef.value?.clearValidate('password')
        })
    }

    const updateUser = (row: any) => {
        title.value = '编辑用户'
        Object.assign(userParams, row)
        isShow.value = true
        nextTick(() => {
            ruleFormRef.value?.clearValidate('username')
            ruleFormRef.value?.clearValidate('name')
        })
    }

    const submitAddOrUpdate = async () => {
        // console.log(ruleFormRef.value.validate(), '000000000000')
        await ruleFormRef.value.validate()

        console.log(userParams, 111111)
        let res: any = await reqAddOrUpdateUser(userParams)
        console.log(res, 222222)
        if (res.code == 200) {
            isShow.value = false
            ElMessage({
                type: 'success',
                message: userParams.id ? '更新成功' : '更新成功'
            })
            if (!userParams.id) {
                getUserList(1)
            } else {
                getUserList(userParams.id ? pageNo.value : 1)
                window.location.reload()    // 浏览器自动刷新一次
            }
            // getUserList(userParams.id ? pageNo.value : 1)
            // window.location.reload()    // 浏览器自动刷新一次
        } else {
            isShow.value = false
            ElMessage({
                type: 'error',
                message: userParams.id ? '更新失败' : '更新失败'
            })
        }
    }

    const setRole = async (row: any) => {
        Object.assign(userParams, row)
        let res = await reqAllRole((userParams.id as number))
        if (res.code == 200) {
            roleArr.value = res.data.allRolesList
            userRole.value = res.data.assignRoles
            isShow2.value = true
        } else {
            ElMessage({
                type: 'error',
                message: '获取失败'
            })
        }
    }

    const handleCheckAllChange = (val: boolean) => {
        // console.log(val, 1)
        userRole.value = val ? roleArr.value : []
        isIndeterminate.value = false
    }

    const handleCheckedCitiesChange = (val: string[]) => {
        console.log(val)
        const checkCount = val.length
        checkAll.value = checkCount === roleArr.value.length
        isIndeterminate.value = !(checkCount === roleArr.value.length)
    }

    const submitSetRole = async () => {
        let data: SetRoleData = {
            userId: userParams.id as number,
            roleIdList: userRole.value.map(item => (item.id as number))
        }
        let res: any = await reqSetUserRole(data)
        if (res.code == 200) {
            ElMessage({
                type: 'success',
                message: '分配职务成功'
            })
            isShow2.value = false
            getUserList(pageNo.value)
        } else {
            ElMessage({
                type: 'error',
                message: '分配职务失败'
            })
        }
    }

    const deleteUser = async (userId: number) => {
        let res = await reqRemoveUser(userId)
        if (res.code == 200) {
            ElMessage({
                type: 'success',
                message: '删除成功'
            })
            getUserList(records.value.length > 1 ? pageNo.value : pageNo.value - 1)
        } else {
            ElMessage({
                type: 'success',
                message: '删除失败'
            })
        }
    }

    const selectChange = (value: any) => {
        console.log(value)
        selectArr.value = value.map((item: any) => (item.id as number))
        console.log(selectArr.value)
    }

    const deleteUserList = async () => {
        console.log('删除', selectArr.value)
        let res = await reqRemoveUserList(selectArr.value)
        if (res.code == 200) {
            ElMessage({
                type: 'success',
                message: '删除成功'
            })
            getUserList(records.value.length > 1 ? pageNo.value : pageNo.value - 1)
        } else {
            ElMessage({
                type: 'success',
                message: '删除失败'
            })
        }
    }

    onMounted(() => {
        getUserList()
    })
</script>

<style scoped lang="scss">
    .query-form {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
</style>